<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook{
	
	function __construct() {
		$this->ci =& get_instance();
		$this->ci->load->config();
		$this->ci->load->config('houseme', TRUE);
		//$this->ci->load->library('security');
		$this->ci->load->library('session');
		$this->ci->load->helper('cookie');
		$this->ci->load->model('user_model');

		
	}
	
	public function getAppAccessToken(){
		$app_id = $this->ci->config->item('fb_app_id', 'houseme');
	    $app_secret = $this->ci->config->item('fb_app_secret', 'houseme');
	    $app_token_url = "https://graph.facebook.com/oauth/access_token?"
        . "client_id=" . $app_id
        . "&client_secret=" . $app_secret 
        . "&grant_type=client_credentials";

        $response = file_get_contents($app_token_url);
        $params = null;
    	parse_str($response, $params);
		return $params['access_token'];
    	//echo("This app's access token is: " . $params['access_token']);
	}
	
	public function login($redirect='',$state=''){

		$app_id = $this->ci->config->item('fb_app_id', 'houseme');
        $app_secret = $this->ci->config->item('fb_app_secret', 'houseme');
		if($redirect != ''){
			$my_url = $redirect;
		}
		else $my_url = $this->ci->config->item('redirect_uri', 'houseme');
        
		$login_url = $this->ci->config->item('login_url', 'houseme');
        $token_url = $this->ci->config->item('token_url', 'houseme');
		$graph_url = $this->ci->config->item('graph_url', 'houseme');
        $get_data = $this->ci->input->get(NULL, TRUE);
		$code = @$get_data['code'];
		$user_data = $this->ci->session->userdata('user_data');//get session


        if (empty($code)) {
            /*
             * 登入維持24小時
             */
            $expire_minute = 60 * 60 * 24;
            
            /*
             * 超過登入時效
             */
            if (isset($user_data['LOGIN_INFO']['LAST_LOGIN_TIME']) && (time() - $user_data['LOGIN_INFO']['LAST_LOGIN_TIME'] > $expire_minute)) {
            	echo "<pre>111:";print_r($this->ci->session->all_userdata());echo "</pre>";exit;
            	//$this->ci->session->sess_destroy();// destroy session data in storage
                $dialog_url = $login_url."client_id=".$app_id."&redirect_uri=".urlencode($my_url).'&state='.$state.'&scope=email';
                echo("<script> top.location.href='".$dialog_url."'</script>");
				exit;
            }
            
            /*
             * 尚未login
             */
            
            if (!isset($user_data['LOGIN_INFO']['LAST_LOGIN_TIME']) || !isset($user_data['LOGIN_INFO']['LOGIN_CODE'])) {
                $dialog_url = $login_url."client_id=".$app_id."&redirect_uri=".urlencode($my_url).'&state='.$state.'&scope=email';
                echo("<script> top.location.href='".$dialog_url."'</script>");
				exit;
            }
        
            
            if ( empty($code) && !isset($user_data['LOGIN_INFO']['LOGIN_CODE'])) {
                $dialog_url = $login_url."client_id=".$app_id."&redirect_uri=".urlencode($my_url).'&state='.$state.'&scope=email';
                echo("<script> top.location.href='".$dialog_url."'</script>");
				exit;
            }
        }
		
		if(isset($user_data['LOGIN_INFO']['LOGIN_CODE'])){ // login already
			echo("<script> top.location.href='".$my_url."'</script>");
			exit;
		}
		
        /*
		 * 確認login code 正確
		 * 並拉回user info
		 */
		
		$code = isset($get_data["code"])?$get_data["code"]:$user_data['LOGIN_INFO']['LOGIN_CODE'];
		
        $token_url = $token_url."client_id=".$app_id."&redirect_uri=".urlencode($my_url)."&client_secret=".$app_secret."&expires_in=86400&code=".$code;
		
        $access_token = @file_get_contents($token_url);
        $graph_url = $graph_url.$access_token;
        //echo $graph_url;exit;
        $user = json_decode(@file_get_contents($graph_url));
        //echo "<pre>";print_r($user);echo "</pre>";exit;
		if(isset($user->id)){
			/*
			 * 確認登入成功
			 */
			$newdata = array();
			$newdata['LOGIN_INFO']['LOGIN_CODE'] = $code;
			$newdata['LOGIN_INFO']['ACCESS_TOKEN'] = $access_token;
        	$newdata['LOGIN_INFO']['LAST_LOGIN_TIME'] = time();
			$newdata['LOGIN_INFO']['id'] = $user->id;
			$newdata['LOGIN_INFO']['name'] = $user->name;
			$newdata['LOGIN_INFO']['gender'] = $user->gender;
			$newdata['LOGIN_INFO']['last_name'] = $user->last_name;
			$newdata['LOGIN_INFO']['first_name'] = $user->first_name;
			$newdata['LOGIN_INFO']['email'] = $user->email;
			$newdata['LOGIN_INFO']['account_type'] = 'fb';
			$newdata['LOGIN_INFO']['link'] = $user->link;

			
			//檢查是否DB裡已有記錄，如果有，就拿記錄來覆蓋session
			$newdata = $this->ci->user_model->checkFBUserSession($user->id,$newdata);

			$this->ci->session->set_userdata('user_data',$newdata);
			
			$this->ci->user_model->checkIfUserSetUp($newdata['LOGIN_INFO']);
			
		}
		else{
			$user = false;
		}
		
		
		return $user;
	}
	
	function logout(){
		$user_data = $this->ci->session->userdata('user_data');//get session
		$this->ci->session->sess_destroy();// destroy session data in storage
		echo("<script> top.location.href='".($this->ci->config->item('logout_url', 'houseme'))."&".$user_data['LOGIN_INFO']['ACCESS_TOKEN']."'</script>");
		exit;
	}	
	
	function checkLoginStatus(){
		$user_data = $this->ci->session->userdata('user_data');//get session
		/*
		 * 登入維持24小時
		 */
		$expire_minute = 60*60*24;
		
		/*
		 * 超過登入時效
		 */
		//echo time();exit;
        if (isset($user_data['LOGIN_INFO']['LAST_LOGIN_TIME']) && (time() - $user_data['LOGIN_INFO']['LAST_LOGIN_TIME'] > $expire_minute)) {
            $this->ci->session->sess_destroy();// destroy session data in storage
			
            return false;
        }
		elseif(!isset($user_data['LOGIN_INFO']['LAST_LOGIN_TIME']) || !isset($user_data['LOGIN_INFO']['LOGIN_CODE'])){
			return false;
		}
		else{
			return true;
		}
	}
	
}


?>